from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAdminUser

from orders.models import OrderInfo
from meiduo_admin.serializers.orders import OrderInfoSerializer, OrderDetailSerializer,OrderStatusSerializer


# GET /meiduo_admin/orders/?keyword=<搜索内容>&page=<页码>&pagesize=<页容量>
class OrdersViewSet(ReadOnlyModelViewSet):
    """订单详情"""
    permission_classes = [IsAdminUser]
    # 指定序列化器
    # serializer_class = OrderInfoSerializer

    def get_serializer_class(self):

        if self.action == 'list':
            return OrderInfoSerializer
        else:
            return OrderDetailSerializer

    # 指定查询集
    def get_queryset(self):

        keyword = self.request.query_params.get('keyword')
        if keyword:
            return OrderInfo.objects.filter(skus__sku__name__contains=keyword) #skus__sku__name__contains=keyword
        else:
            return OrderInfo.objects.all()

    # PUT /meiduo_admin/orders/(?P<pk>\d+)/status/
    @action(methods=['put'], detail=True)
    def status(self,request, pk):

        queryset = OrderInfo.objects.get(order_id=pk)

        serializer = OrderStatusSerializer(queryset,data=request.data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.validated_data)



